package cn.hml.org.controller;

import cn.hml.basic.util.AjaxResult;
import cn.hml.basic.util.PageList;
import cn.hml.org.domain.Employee;
import cn.hml.org.query.EmployeeQuery;
import cn.hml.org.service.IEmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
//@Controller
//@ResponseBody
@RequestMapping("/employee")
@CrossOrigin
@Api(value = "部门接口类",description = "处理部门的所有请求")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 接口：查询单个对象
     * @param id
     * @return
     */
    //写一个接口/方法：1.请求方式 2.请求参数 3.请求地址 4.返回数据格式
    //Get http://localhost/employee/1
    @GetMapping("/{id}")
    @ApiOperation("查询单个对象")
    //@PathVariable("id") Long id - 从路径上去获取变量 id 赋值给 Long id
    public Employee loadById(@PathVariable("id") Long id){
        return employeeService.loadById(id);
    }

    /**
     * 接口：查询所有
     * @return
     */
    //Get http://localhost/employee
    @GetMapping
    @ApiOperation("查询所有对象")
    public List<Employee> loadAll(){
        return employeeService.loadAll();
    }

    /**
     * 接口：分页查询
     * @param employeeQuery
     * @return
     */
    //post http://localhost/employee 对象
    @PostMapping
    @ApiOperation("分页查询")
    public PageList<Employee> queryPage(@RequestBody EmployeeQuery employeeQuery){
        return employeeService.queryPage(employeeQuery);
    }

    /**
     * 删除接口
     * @param id
     * @return
     */
    //delete http://localhost/employee/1
    @DeleteMapping("/{id}")
    @ApiOperation("删除单个对象")
    public AjaxResult delete(@PathVariable("id")Long id){
        try {
            employeeService.del(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    /**
     * 添加和修改接口
     * @param employee
     * @return
     */
    //put http://localhost/employee {对象}
    @PutMapping
    @ApiOperation("添加或修改")
    public AjaxResult addOrUpdate(@RequestBody Employee employee){
        try {
            if(employee.getId() == null){
                employeeService.sava(employee);
            }else{
                employeeService.update(employee);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }


    /**
     * 接口：批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    @ApiOperation("批量删除对象")
    public AjaxResult patchDel(@RequestBody Long[] ids){
        try {
            employeeService.patchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

}
